//package com.dgm.kernel.web.aspect;
//
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.core.util.StrUtil;
//import cn.hutool.json.JSONArray;
//import cn.hutool.json.JSONObject;
//import cn.hutool.json.JSONUtil;
//import UserEntity;
//import LogEntity;
//import GlobalExceptionHandler;
//import com.google.common.collect.Lists;
//import lombok.extern.slf4j.Slf4j;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.reflect.MethodSignature;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
//import org.springframework.stereotype.Component;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.lang.reflect.Method;
//import java.util.Arrays;
//import java.util.List;
//import java.util.Map;
//
//
///**
// * 对RestController切面 统一打印日志
// * @author haoqizhe.li
// * @date 2018/4/2 22:03
// */
//@Aspect
//@Component
//@Slf4j
//@ConditionalOnProperty(prefix = "controller.aspect.log",name="enabled",havingValue = "enabled",matchIfMissing = false)
//public class ControllerAspect {
//
////    @Autowired
////    @Qualifier(value="redisTemplate")
////    RedisTemplate redisTemplate;
//    @Value("${controller.aspect.log.start-log:'开始请求 服务器IP [{}] 请求者 [{}] 请求方法 [{}] 请求参数 [{}] 请求IP [{}] 调用来源 [{}] APP版本 [{}] 接口文档版本 [{}] userAgent [{}]'}")
//    private String startLog;
//    @Value("${controller.aspect.log.end-log:'结束请求 服务器IP [{}] 请求者 [{}] 请求方法 [{}] 请求参数 [{}] 接口返回 [{}] 耗时 [{}] 毫秒'}")
//    private String endLog;
//    @Value("${controller.aspect.log.sensitive-fields:#{null}}")
//    private String fields;
//
//    /**
//    * 环绕通知
//    * @return object
//    * @throws
//    * @author haoqizhe.li
//    * @date 2018/4/2 22:10
//    **/
//    @Around("@within(org.springframework.web.bind.annotation.RestController) || @annotation(org.springframework.web.bind.annotation.RestController)")
//    public Object apiLog(ProceedingJoinPoint point) throws Throwable {
//        MethodSignature signature = (MethodSignature)point.getSignature();
//        Method method = signature.getMethod();
//        boolean logFlag = this.needToLog(method);
//        if (!logFlag) {
//            return point.proceed();
//        }
//
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        UserEntity loginUser = LoginHelper.getLoginUserFromRequest(request,redisTemplate);
//
//        String methodName = this.getMethodName(point);
//        String params = this.getParamsJson(point);
//
//        LogEntity logEntity = LogEntity.getLogEntity(null,request,loginUser);
//
//        log.info(startLog,logEntity.getServerIp(), logEntity.getRequester(), methodName, params, logEntity.getRequestIp(),
//                logEntity.getCallSource(), logEntity.getAppVersion(), logEntity.getApiVersion(), logEntity.getUserAgent());
//
//        long start = System.currentTimeMillis();
//
//        Object result = point.proceed();
//
//        log.info(endLog,logEntity.getServerIp(),logEntity.getRequester(), methodName, params, this.deleteSensitiveContent(result), System.currentTimeMillis() - start);
//        return result;
//    }
//
//    private String getMethodName(ProceedingJoinPoint joinPoint) {
//        String methodName = joinPoint.getSignature().toShortString();
//        String SHORT_METHOD_NAME_SUFFIX = "(..)";
//        if (methodName.endsWith(SHORT_METHOD_NAME_SUFFIX)) {
//            methodName = methodName.substring(0, methodName.length() - SHORT_METHOD_NAME_SUFFIX.length());
//        }
//        return methodName;
//    }
//
//    private String getParamsJson(ProceedingJoinPoint joinPoint) {
//        Object[] args = joinPoint.getArgs();
//        StringBuilder sb = new StringBuilder();
//        for (Object arg : args) {
//            //移除敏感内容
//            String paramStr;
//            if (arg instanceof HttpServletResponse) {
//                paramStr = HttpServletResponse.class.getSimpleName();
//            } else if (arg instanceof HttpServletRequest) {
//                paramStr = HttpServletRequest.class.getSimpleName();
//            } else if (arg instanceof MultipartFile) {
//                long size = ((MultipartFile) arg).getSize();
//                paramStr = MultipartFile.class.getSimpleName() + " size:" + size;
//            } else {
//                paramStr = this.deleteSensitiveContent(arg);
//            }
//            sb.append(paramStr).append(",");
//        }
//        return sb.deleteCharAt(sb.length() - 1).toString();
//    }
//
//    /**
//     * 判断是否需要记录日志
//     */
//    private boolean needToLog(Method method) {
//        return method.getAnnotation(GetMapping.class) == null
//                && !method.getDeclaringClass().equals(GlobalExceptionHandler.class);
//    }
//
//    /**
//     * 删除参数中的敏感内容
//     * @param obj 参数对象
//     * @return 去除敏感内容后的参数对象
//     */
//    private String deleteSensitiveContent(Object obj) {
//        JSONObject jsonObject = null;
//        List<Map> list = null;
//
//        boolean ex = obj == null || obj instanceof Exception || (obj instanceof List && ((List) obj).size() == 0 );
//        if (ex) {
//            jsonObject = new JSONObject();
//            return jsonObject.toString();
//        }
//
//        try {
//            String param = JSONUtil.toJsonStr(obj);
//            List<String> sensitiveFieldList = this.getSensitiveFieldList();
//
//            if (param.startsWith("[")) {
//                JSONArray jsonArray = JSONUtil.parseArray(param);
//                list = JSONUtil.toList(jsonArray,Map.class);
//                if(CollUtil.isNotEmpty(list)){
//                    for(Map map : list){
//                        for (String sensitiveField : sensitiveFieldList) {
//                            if (map.containsKey(sensitiveField)) {
//                                map.put(sensitiveField, "******");
//                            }
//                        }
//                    }
//                    return JSONUtil.toJsonStr(list);
//                }
//            } else if(param.startsWith("{")){
//                jsonObject = JSONUtil.parseObj(param);
//                if(jsonObject != null){
//                    for (String sensitiveField : sensitiveFieldList) {
//                        if (jsonObject.containsKey(sensitiveField)) {
//                            jsonObject.put(sensitiveField, "******");
//                        }
//                    }
//                    return jsonObject.toString();
//                }
//            }
//        } catch (ClassCastException e) {
//            return String.valueOf(obj);
//        }
//        return String.valueOf(obj);
//    }
//
//    /**
//     * 敏感字段列表（当然这里你可以更改为可配置的）
//     */
//    private List<String> getSensitiveFieldList() {
//        List<String> sensitiveFieldList = Lists.newArrayList();
//        if(StrUtil.isNotBlank(fields)){
//            sensitiveFieldList.addAll(Arrays.asList(fields.split(",")));
//        }
//        return sensitiveFieldList;
//    }
//}
